//
//  FLAudioMusicDBManager.m
//  FeeLing
//
//  Created by 乔光玉 on 2019/1/10.
//  Copyright © 2019年 大仙儿飘. All rights reserved.
//
#import "FLCacheManager.h"
#import "FLAudioObject.h"
#import "FLAudioMusicDBManager.h"
#define mainBundleDBName @"FLAudioMusicDB.sqlite"
@implementation FLAudioMusicDBManager
static FLAudioMusicDBManager * manager = nil;
static dispatch_once_t once;

+ (instancetype)sharedManager
{
    
    
    dispatch_once(&once, ^{
        if (!manager) {
            manager = [[self alloc] init];
            
            
            NSString * dbFilePath = nil;
            
            dbFilePath =[[FLCacheManager documentDirectory] stringByAppendingPathComponent:mainBundleDBName];
            
            [manager connectDBWithPath:dbFilePath];
            [manager upgradeDB];
            
            
        }
    });
    return manager;
    
}
-(instancetype)init
{
    self = [super init];
    if (self) {
       
    }
    return self;
}
-(void)dealloc
{
    
}

/**
 * 设置nil，并清空数据
 */
-(void)clearSelf
{
    [super clearSelf];
    
    manager = nil;
    once = 0;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  新增一个要学习的单词
 *
 *  @param focusItem 单词
 *
 *  @return 执行结果
 */
- (BOOL)insertAudioWith:(FLAudioObject *)focusItem

{
    if (![self.database open] || !focusItem) {
        return NO;
    }
    __block BOOL success = YES;
    //TODO:先判断是否存在word的数据
    //如果存在，就直接return YES；
    if ([self isExistAudio:focusItem.name]) {
        
        return YES;
    }
    
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        NSString *sqlString = [NSString stringWithFormat:@"insert into FLAudiosList (name,url,type,time,localam) values ('%@', '%@', '%ld','%@','%@')", focusItem.name,focusItem.url,focusItem.type,focusItem.time,focusItem.localam];
        
        [db executeUpdate:sqlString];
        
        if ([db hadError]) {
            NSLog(@"insert FLAudiosList error = %@", [db lastError]);
            
            success = NO;
        }
    }];
    
    return success;
}

- (BOOL)updateAudioWith:(FLAudioObject *)focusItem
{
    if (![self.database open] || !focusItem) {
        return NO;
    }
    __block BOOL success = YES;
    //TODO:先判断是否存在objectId的数据
    //如果不存在就直接写入
    if (![self isExistAudio:focusItem.name]) {
        
        [self insertAudioWith:focusItem] ;
        
    }
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        
        [db executeUpdateWithFormat:@"update FLAudiosList set localam = %@, url = %@,type = %ld, time = %@  where name = %@",focusItem.localam,focusItem.url,focusItem.type,focusItem.time,focusItem.name];
        
        
        
        if ([db hadError]) {
            NSLog(@"update objectId error = %@", [db lastError]);
            
            success = NO;
        }
    }];
    
    return success;
}

- (BOOL)deleteAudioWith:(NSString *)object;
{
    
    
    
    if (![self.database open] || !object) {
        return NO;
    }
    __block BOOL success = YES;
    
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        [db executeUpdateWithFormat:@"delete from FLAudiosList where name = %@", object];
        
        if ([db hadError]) {
            NSLog(@"delete audios error = %@", [db lastError]);
            
            success = NO;
        }
    }];
    
    return success;
    
}





/**
 *得到已掌握单词的数量
 */


- (NSArray *)getAllGraspAudios{
    if (![self.database open]) {
        return 0;
    }
    __block NSMutableArray *array = [[NSMutableArray alloc] init];
    
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *rs = [db executeQuery:@"select * from FLAudiosList "];
        
        while ([rs next]) {
            NSDictionary *dict = [rs resultDictionary];
            
            FLAudioObject *Items = [[FLAudioObject alloc] init];
            [Items parseFromDbData:dict];
            
            [array addObject:Items];
        }
        
        [rs close];
    }];
    
    return array;
}
- (NSArray *)getOneoObjectAudiosWith:(NSInteger) type{
    
    if (![self.database open]) {
        return 0;
    }
    __block NSMutableArray *array = [[NSMutableArray alloc] init];
    
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *rs = [db executeQueryWithFormat:@"select * from FLAudiosList where type = %ld", type];
        
        while ([rs next]) {
            NSDictionary *dict = [rs resultDictionary];
            
            FLAudioObject *Items = [[FLAudioObject alloc] init];
            [Items parseFromDbData:dict];
            
            [array addObject:Items];
        }
        
        [rs close];
    }];
    
    return array;
    
    
}

-(BOOL)isExistAudio:(NSString*)object
{
    
    if (![self.database open]) {
        return NO;
    }
    __block BOOL success = NO;
    
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *rs = [db executeQueryWithFormat:@"select * from FLAudiosList where name = %@  ",object];
        
        if ([rs next]) {
            
            success = YES;
            
        }
        [rs close];
    }];
    
    return success;
    
    
}




-(BOOL)upgradeDB;
{
    [super upgradeDB];
    if (![manager isExistTable:@"FLAudiosList"]) {
        
        [self.databaseQueue inDatabase:^(FMDatabase *db) {
            
            
            NSString * sql = @"CREATE TABLE 'FLAudiosList' ('name' VARCHAR PRIMARY KEY, 'url' VARCHAR,'localam' VARCHAR,'time' VARCHAR,'type' INTEGER);";
            
            FMResultSet *rs = [db executeQuery:sql];
            if ([rs next]) {
                [self setDBInfoVersion:1];
            }
            [rs close];
            
            
            
        }];
        
        
    }
    
    if (![self isExistTable:@"dbInfo"]) {
        [self.databaseQueue inDatabase:^(FMDatabase *db) {
            NSString * sql = @"CREATE TABLE 'dbInfo' ('version' INTEGER, 'id' INTEGER PRIMARY KEY AUTOINCREMENT)";
            
            FMResultSet *rs = [db executeQuery:sql];
            if ([rs next]) {
                [self setDBInfoVersion:1];
            }
            [rs close];
            
        }];
        
    }
    
    NSInteger version = [self getDBInfoVersion];
    switch (version) {
        case 0:
            
        default:
            break;
    }
    
    
    
    return YES;
}

@end
